package worst.shopping.main;

import worst.shopping.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;

public class SplashScreenActivity extends Activity {
	
	//splash screen visibility in ms
	private final int _splashTime = 5000;
	private final SplashScreenActivity _self = this;
	
	private Thread _showSplashScreenThread;
	private Boolean _closeApp = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);
        
        _showSplashScreenThread = new Thread()
        {
        	public void run()
        	{
        		try {
        			synchronized (this) {
        				//wait the time the splashscreen should be shown
						wait(_splashTime);
					}
					
				} catch (Exception e) {
					// TODO: handle exception
				}
        		finally {
        			//finish splashscreen activity so it wont show up
        			//if the user hits the back button
        			finish();
        			
        			//if the user hasnt pressed the back button while 
        			//looking at the wonderful splashscreen, start
        			//the actualy application
        			if(!_closeApp)
        			{
            			//start real app
            			Intent intent = new Intent(_self, MainActivity.class);
            			startActivity(intent);
        			}
        		}
        	}
        };
        
        _showSplashScreenThread.start();
    }
    
    /**
     * Exits the Splash Screen Activity
     * 
     * @param closeApp defines if the app should be closed after quitting the splash screen
     */
    private void exitSplashScreen(Boolean closeApp)
    {
        synchronized(_showSplashScreenThread)
        {
            _closeApp = closeApp;
            _showSplashScreenThread.notifyAll();
        }   	
    }
    
    @Override
    public void onBackPressed()
    {
    	//if the user hits the back button while the splashscreen is visible
    	//exit the app
    	exitSplashScreen(true);
    }    
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    	//if the user touches the display, continue with app execution without
    	//waiting for the timer
    	exitSplashScreen(false);
    	
    	return true;
    }
}